package DAOs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import Conexao.ConnectionManager;
import modelo.Cd;

class CdDAOImp implements CdDAO{
	
	private final String INSERT = "insert into Cd (titulo,ano,ehColetanea,ehDuplo) values (?,?,?,?)";
	private final String UPDATE = "update Cd set titulo = ?, ano = ?, ehColetanea=?, ehDuplo = ? where codCd = ?";
	private final String DELETE = "delete from Cd where codCd = ?";
	private final String ALL = "select codCd, musica, titulo from Cd";
	private final String LIKE = "select musica, titulo, ehColetania, ehDuplo from Cd where codCd like ?";

	private ConnectionManager connectionManager;
	private static Connection connection;
	
	
	
	public Cd salvar(Cd e) {
		try {
			PreparedStatement ps = null;
			//1 crie um instancia de PreparedStatement
			//para obter a chave gerada pelo banco
			ps = connection.prepareStatement(INSERT);
			
			ps.setObject(1, e.getTitulo());
			ps.setObject(2, e.getAno());
			ps.setObject(3, e.isEhColetanea());
			ps.setObject(4, e.isEhDuplo());
			
			ps.executeUpdate();
			
		} catch (SQLException ex) {
			Logger.getLogger(CdDAOImp.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			this.closeConnection();
		}
		return e;
	}

	public void alterar(Cd e) {

		PreparedStatement ps = null;
		try {
			//2 crie uma instancia de PreparedStatement 
			//passe para ela a instrucao para realizar alteracoes em uma registro do banco 
			ps = connection.prepareStatement(UPDATE);
			
			//"update cd set  = ?, titulo = ?, ano = ?, hColetania=?, ehDuplo = ? where codCd = ?";	
			
			ps.setObject(1, e.getTitulo());
			ps.setObject(2, e.getAno());
			ps.setObject(3, e.isEhColetanea());
			ps.setObject(3, e.isEhDuplo());
			
			ps.executeUpdate();

		} catch (SQLException ex) {
			Logger.getLogger(CdDAOImp.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			this.closeConnection();
		}
		
	}

	@Override
	public void deletar(Cd e) {
		try {
			PreparedStatement ps = null;
			ps = connection.prepareStatement(DELETE);
			//3 passe para o PreparedStatement o valor do id que deve ser excluido do banco de dados 
			ps.setObject(1, e.getCodCd());
			
			ps.executeUpdate();

		} catch (SQLException ex) {
			Logger.getLogger(CdDAOImp.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			this.closeConnection();
		}
		
	}

	public List<Cd> findAll() {
		List<Cd> cds = new ArrayList<Cd>();

		try {
			PreparedStatement ps = null;
			ResultSet rs = null;
			ps = connection.prepareStatement(ALL);
			
			rs = ps.executeQuery();
			
			while (rs.next()) {
				Cd cd = new Cd();
				cd.setTitulo(rs.getString(1));
				cd.setAno(rs.getInt(2));
				cd.setEhColetanea(rs.getBoolean(3));
				cds.add(cd);
				//5 crie uma instancia de cidade com os dados
				//obtidos do banco e adicione a lista de cidades
				
			}

		} catch (SQLException ex) {
			Logger.getLogger(CdDAOImp.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			this.closeConnection();
		}
		return cds;
	}

	public boolean isConnectionClose() {
		try {
			return connection.isClosed();
		} catch (SQLException ex) {
			return false;
		}
	}

	public void openConnection() {
		if ( connectionManager == null ) {
			connectionManager = ConnectionManager.getInstance();
		}
		
		if ( connection == null) {
			connection = connectionManager.getConnection();
		}
		
		if ( isConnectionClose() ) {
			connection = connectionManager.getConnection();
		}
		
	}

	public void closeConnection() {
		if ( connection != null && connectionManager != null) {
			if ( ! this.isConnectionClose() ) {
				connectionManager.closeConnection(connection);
			}
		}
	}

	@Override
	public List<Cd> buscaMusicosPorNome(Cd cd) {
		List<Cd> cds = new ArrayList<Cd>();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = connection.prepareStatement(LIKE);
			//6 informe o parmetro para instrucao like
			ps.setObject(1, cd.getTitulo());
		
			rs = ps.executeQuery();

			while (rs.next()) {
				cds.add(new Cd(
						rs.getInt("codCd"),
						rs.getInt("codMusica"),
						rs.getBoolean("ehDuplo"),
						rs.getString("titulo"),
						rs.getInt("ano"),
						rs.getBoolean("ehColetanea")));
			}

		} catch (SQLException ex) {
			Logger.getLogger(CdDAOImp.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			this.closeConnection();
		}
		return cds;
	}
}
